const { DataTypes } = require('sequelize');

/**
 * 订单模型
 */
module.exports = (sequelize) => {
  const Order = sequelize.define('Order', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    order_no: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
      comment: '订单号'
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '用户ID'
    },
    order_type: {
      type: DataTypes.ENUM('reservation', 'recharge'),
      allowNull: false,
      comment: '订单类型：reservation-预约订单，recharge-充值订单（包括优惠券购买）'
    },
    reservation_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '预约ID（仅预约订单有）'
    },
    amount: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      comment: '订单金额'
    },
    status: {
      type: DataTypes.ENUM('pending', 'paid', 'canceled', 'refunded', 'expired'),
      allowNull: false,
      defaultValue: 'pending',
      comment: '订单状态：pending-待支付，paid-已支付，canceled-已取消，refunded-已退款，expired-已过期'
    },
    payment_method: {
      type: DataTypes.ENUM('wechat', 'alipay', 'balance'),
      allowNull: true,
      comment: '支付方式：wechat-微信支付，alipay-支付宝，balance-余额支付'
    },
    payment_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '支付时间'
    },
    transaction_id: {
      type: DataTypes.STRING(64),
      allowNull: true,
      comment: '支付交易号'
    },
    remark: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '备注'
    }
  }, {
    tableName: 'orders',
    timestamps: true,
    createdAt: 'create_time',
    updatedAt: 'update_time',
    indexes: [
      { fields: ['user_id'] },
      { fields: ['order_no'] },
      { fields: ['reservation_id'] }
    ]
  });

  // 添加关联关系
  Order.associate = (models) => {
    // 订单与用户的关系
    Order.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user'
    });

    // 订单与预约的关系
    Order.belongsTo(models.Reservation, {
      foreignKey: 'reservation_id',
      as: 'reservation'
    });
  };

  return Order;
}; 